using System;
using System.Collections.Generic;
using System.Text;


using System.Data;
using System.IO;
using System.CodeDom.Compiler;
using System.CodeDom;
using Microsoft.CSharp;
using System.Data.SqlClient;
using System.Reflection;

using System.Xml.Schema;
using ESBSimpleSamples.ServiceClient.Generator.WSDL;

namespace ESBSimpleSamples.ServiceClient.Generator.Scripts
{
    /// <summary>
    /// Generates the XSD for a WSDL endpoint
    /// </summary>
    public class SchemaScript : XmlScript
    {
        private string ServiceProviderName
        {
            get
            {
                string parameterValue = this.GetParameterValue("serviceProviderName");
                if (string.IsNullOrEmpty(parameterValue))
                {
                    string[] namespaceParts = this.Namespace.Split('.');
                    parameterValue = namespaceParts[0];
                    this.ServiceProviderName = parameterValue;
                }
                return parameterValue;
            }
            set { this.SetParameterValue("serviceProviderName", value); }
        }

        private string Namespace
        {
            get
            {
                string parameterValue = this.GetParameterValue("namespace");
                if (string.IsNullOrEmpty(parameterValue))
                {
                    string[] namespaceParts = this._metadata.TargetNamespace.Replace(@"//", @"/").Split('/');
                    parameterValue = namespaceParts[1];
                    this.Namespace = parameterValue;
                }
                return parameterValue;
            }
            set { this.SetParameterValue("namespace", value); }
        }

        public override string Name
        {
            get { return "Schema"; }
        }

        protected override void Process()
        {
                this.OutputXml();
        }

        protected override void WriteTo(System.Xml.XmlWriter writer)
        {
            XmlSchema schema = this._metadata.Schema;
            //remove the SOAP and WSDL imports, as we don't need them and BizTalk won't like them:
            List<XmlSchemaImport> importsToRemove = new List<XmlSchemaImport>();
            foreach (XmlSchemaImport import in schema.Includes)
            {
                if (import.Namespace == @"http://schemas.xmlsoap.org/soap/encoding/" ||
                    import.Namespace == @"http://schemas.xmlsoap.org/wsdl/")
                {
                    importsToRemove.Add(import);
                }
            }
            foreach (XmlSchemaImport import in importsToRemove)
            {
                schema.Includes.Remove(import);
            }
            schema.Write(writer);
        }
    }
}